<template>
    <table width="600px" border="1" style="border-collapse: collapse;">
        <caption>购物车</caption>
        <thead>
            <tr>
                <th>
                    <input type="checkbox" v-model="isAll">
                    <span>全选</span>
                </th>
                <th>名称</th>
                <th>价格</th>
                <th>数量</th>
                <th>总价</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <!-- 使用vue组件 -->
            <Search v-for="(obj,index) in goodList" :key="index" :obj="obj" @del="deleteFn"></Search>
        </tbody>
        <tfoot>
            <!-- 价格总量区 -->
            <tr>
                <td>合计:</td>
                <td colspan="5">{{allPrice}}</td>
            </tr>
        </tfoot>
    </table>

</template>

<script>
import Search from './Search.vue';
export default {
    data() {
        return {
            goodList: [
                {
                    name: '诸葛亮',
                    price: 200,
                    num: 1,
                    checked: false,
                },
                {
                    name: '鲁班',
                    price: 100,
                    num: 1,
                    checked: false,
                },
                {
                    name: '孙尚香',
                    price: 300,
                    num: 1,
                    checked: false,
                },
                {
                    name: '嬴政',
                    price: 450,
                    num: 1,
                    checked: false,
                },
                {
                    name: '公孙离',
                    price: 200,
                    num: 1,
                    checked: false,
                },
            ]
        };
    },
    computed: {

        isAll: {
            // 实现全选功能，当全选的checked为true时，其遍历的数组中的checked状态也会改变为
            set(val) {
                this.goodList.forEach((obj) => (obj.checked = val));
            },
            //every()是数组的方法
            //遍历数组的每一项,找到第一个不符合条件的,直接原地返回一个false
            get() {
                return this.goodList.every(obj => obj.checked === true);
            }
        },
        // 合计总量的判断
        allPrice() {
            return this.goodList.reduce((sum, obj) => {
                // 判断只有当被选中时，才会进行累加 对象 obj
                if (obj.checked === true) {
                    sum += obj.price * obj.num
                }
                return sum;
            }, 0)
        }
    },
    components: {
        Search,
    },

    methods: {
        deleteFn(index) {
            this.goodList.splice(index, 1);
        }
    }
};
</script>

<style scoped lang="scss">
table {
    text-align: center;
}
</style>
